package org.bling.star.server.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.bling.star.common.command.BaseCommand;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

public class CommandDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return; // 不足4个字节，无法读取长度
        }

        in.markReaderIndex();
        int dataLength = in.readInt();

        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex(); // 数据不足，重置读取索引
            return;
        }

        byte[] data = new byte[dataLength];
        in.readBytes(data);

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
        BaseCommand command = (BaseCommand) ois.readObject();
        out.add(command);
    }
}